/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"github.com/BurntSushi/xgb/xproto"
	"github.com/BurntSushi/xgbutil"
	"github.com/BurntSushi/xgbutil/ewmh"
	"log"
)

var X *xgbutil.XUtil

func strIsInInList(key string, list []string) bool {
	for _, v := range list {
		if key == v {
			return true
		}
	}

	return false
}

func getActiveWindow() uint32 {
	xid, err := ewmh.ActiveWindowGet(X)
	if err != nil {
		log.Println("Get active window failed:", err)
		return 0
	}

	return uint32(xid)
}

func isWindowFullscreen(xid uint32) bool {
	list := getWindowState(xid)

	if strIsInInList("_NET_WM_STATE_FULLSCREEN", list) {
		return true
	}

	return false
}

func isWindowMaximize(xid uint32) bool {
	list := getWindowState(xid)

	if strIsInInList("_NET_WM_STATE_MAXIMIZED_VERT", list) &&
		strIsInInList("_NET_WM_STATE_MAXIMIZED_HORZ", list) {
		return true
	}

	return false
}

func isWindowMinimize(xid uint32) bool {
	list := getWindowState(xid)

	if strIsInInList("_NET_WM_ACTION_MINIMIZE", list) {
		return true
	}

	return false
}

func getWindowState(xid uint32) []string {
	list, err := ewmh.WmStateGet(X, xproto.Window(xid))
	if err != nil {
		log.Println("Get window state failed:", err)
	}

	return list
}

func getWindowName(xid uint32) string {
	name, err := ewmh.WmNameGet(X, xproto.Window(xid))
	if err != nil {
		log.Println("Get window name failed:", err)
	}

	return name
}

func getWindowType(xid uint32) []string {
	list, err := ewmh.WmWindowTypeGet(X, xproto.Window(xid))
	if err != nil {
		log.Println("Get window type failed:", err)
	}

	return list
}

func getWindowPid(xid uint32) uint32 {
	pid, err := ewmh.WmPidGet(X, xproto.Window(xid))
	if err != nil {
		log.Println("Get window pid failed:", err)
	}

	return uint32(pid)
}

func main() {
	var err error

	if X, err = xgbutil.NewConn(); err != nil {
		log.Println("New xgbutil failed:", err)
		return
	}

	xid := getActiveWindow()
	log.Println("xid:", xid)
	log.Println("pid:", getWindowPid(xid))
	log.Println("name:", getWindowName(xid))
	log.Println("state:", getWindowState(xid))
	log.Println("type:", getWindowType(xid))
}
